package com.test.VT.PerformanceComparison;

import com.test.VT.Thread.CustomThread;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author caoqianfan
 * @date 2024/9/27 14:17
 */
public class Performance_Thread {

    static List<Integer> list = new ArrayList<>();

    public static void main(String[] args) {
        // 开启一个线程来监控当前的平台线程（系统线程）总数
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
            ThreadInfo[] threadInfo = threadBean.dumpAllThreads(false, false);
            saveMaxThreadNum(threadInfo.length);
        }, 1, 1, TimeUnit.SECONDS);

        long start = System.currentTimeMillis();
        ExecutorService executor = Executors.newFixedThreadPool(200);
        for (int i = 0; i < 100000; i++) {
            CustomThread customThread = new CustomThread();
            executor.submit(customThread);
        }
        executor.close();
        System.out.println("max：" + list.getFirst() + " platform thread/os thread");
        System.out.printf("totalMillis：%dms\n", System.currentTimeMillis() - start);

        //输出结果：
        //max：209 platform thread/os thread
        //totalMillis：7728ms
    }

    // 保存平台线程的创建的最大总数
    public static void saveMaxThreadNum(int num) {
        if (list.isEmpty()) {
            list.add(num);
        } else {
            Integer integer = list.getFirst();
            if (num > integer) {
                list.addFirst(num);
            }
        }
    }
}